"use client";

import { Command, CommandInput } from "@/components/tailwind/ui/command";
import { useCompletion } from "@/hooks/useCompletion";
import { ArrowUp } from "lucide-react";
import { useEditor } from "novel";
import { addAIHighlight } from "novel/extensions";
import { useState } from "react";
import Markdown from "react-markdown";
import { toast } from "sonner";
import { Button } from "../ui/button";
import CrazySpinner from "../ui/icons/crazy-spinner";
import Magic from "../ui/icons/magic";
import { ScrollArea } from "../ui/scroll-area";
import AICompletionCommands from "./ai-completion-command";
import AISelectorCommands from "./ai-selector-commands";
import { PlanUpgradeDialog } from "@/components/PlanUpgradeDialog"; // 新增导入
import { LimitWarning } from "@/components/LimitWarning"; // 新增导入

interface AISelectorProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
}

export function AISelector({ onOpenChange }: AISelectorProps) {
  const { editor } = useEditor();
  const [inputValue, setInputValue] = useState("");
  const [showUpgradeDialog, setShowUpgradeDialog] = useState(false);
  const [limitInfo, setLimitInfo] = useState<any>(null);
  const [showLimitWarning, setShowLimitWarning] = useState(false); // 新增：控制限制警告显示
  const [userId, setUserId] = useState<string>("");

  const { completion, complete, isLoading } = useCompletion({
    api: "/api/generate",
    onResponse: (response) => {
      if (response.status === 429) {
        return;
      }
    },
    onLimitReached: (info) => {
      setLimitInfo(info);
      setShowLimitWarning(true); // 先显示限制警告
      // 显示详细的错误信息
      toast.error(`AI生成次数已达上限！当前使用：${info.currentCount}/${info.limit} 次（${info.planType === 'basic' ? '基础版' : info.planType === 'pro' ? '专业版' : '企业版'}）`);
    },
    onError: (e) => {
      toast.error(e.message);
    },
  });

  const hasCompletion = completion.length > 0;

  return (
    <>
      <Command className="w-[350px]">
        {/* 显示限制警告信息 */}
        {showLimitWarning && limitInfo && (
          <div className="p-4 border-b bg-yellow-50 border-yellow-200">
            <div className="flex items-center justify-between">
              <div>
                <h4 className="font-medium text-yellow-800">AI生成次数已达上限</h4>
                <p className="text-sm text-yellow-700 mt-1">
                  当前套餐：{limitInfo.planType === 'basic' ? '基础版' : limitInfo.planType === 'pro' ? '专业版' : '企业版'}
                </p>
                <p className="text-sm text-yellow-700">
                  使用情况：{limitInfo.currentCount}/{limitInfo.limit} 次
                </p>
              </div>
              <button
                onClick={() => setShowLimitWarning(false)}
                className="text-yellow-600 hover:text-yellow-800"
              >
                ×
              </button>
            </div>
            <div className="mt-3 flex gap-2">
              <button
                onClick={() => {
                  setShowLimitWarning(false);
                  setShowUpgradeDialog(true);
                }}
                className="px-3 py-1 bg-yellow-600 text-white text-sm rounded hover:bg-yellow-700"
              >
                查看升级选项
              </button>
              <button
                onClick={() => setShowLimitWarning(false)}
                className="px-3 py-1 border border-yellow-600 text-yellow-600 text-sm rounded hover:bg-yellow-50"
              >
                稍后再说
              </button>
            </div>
          </div>
        )}
        
        {hasCompletion && (
          <div className="flex max-h-[400px]">
            <ScrollArea>
              <div className="prose p-2 px-4 prose-sm">
                <Markdown>{completion}</Markdown>
              </div>
            </ScrollArea>
          </div>
        )}

        {isLoading && (
          <div className="flex h-12 w-full items-center px-4 text-sm font-medium text-muted-foreground text-purple-500">
            <Magic className="mr-2 h-4 w-4 shrink-0  " />
            AI is thinking
            <div className="ml-2 mt-1">
              <CrazySpinner />
            </div>
          </div>
        )}
        {!isLoading && (
          <>
            <div className="relative">
              <CommandInput
                value={inputValue}
                onValueChange={setInputValue}
                autoFocus
                placeholder={hasCompletion ? "Tell AI what to do next" : "Ask AI to edit or generate..."}
                onFocus={() => {
                  if (!editor) return;
                  addAIHighlight(editor);
                }}
                onKeyDown={(e) => {
                  if (e.key === "Enter" && !e.shiftKey) {
                    e.preventDefault();
                    document.getElementById('ai-submit-button')?.click();
                  }
                }}
              />
              <Button
                id="ai-submit-button"
                size="icon"
                className="absolute right-2 top-1/2 h-6 w-6 -translate-y-1/2 rounded-full bg-purple-500 hover:bg-purple-900"
                onClick={() => {
                  if (completion)
                    return complete(completion, {
                      body: { option: "zap", command: inputValue },
                    }).then(() => setInputValue(""));

                    if (!editor) return;
                  const slice = editor.state.selection.content();
                  const text = editor.storage.markdown.serializer.serialize(slice.content);

                  complete(text, {
                    body: { option: "zap", command: inputValue },
                  }).then(() => setInputValue(""));
                }}
              >
                <ArrowUp className="h-4 w-4" />
              </Button>
            </div>
            {hasCompletion ? (
              <AICompletionCommands
                onDiscard={() => {
                  if (!editor) return;
                  editor.chain().unsetHighlight().focus().run();
                  onOpenChange(false);
                }}
                completion={completion}
              />
            ) : (
              <AISelectorCommands onSelect={(value, option) => complete(value, { body: { option } })} />
            )}
          </>
        )}
      </Command>
      
      {/* 升级对话框 - 只有用户主动选择时才显示 */}
      <PlanUpgradeDialog
        open={showUpgradeDialog}
        onOpenChange={setShowUpgradeDialog}
        currentPlan={limitInfo?.planType || 'free'}
        userId={userId}
      />
    </>
  );
}
